package com.javaforever.clocksimplejee4.facade;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.javaforever.clocksimplejee4.domain.User;
import com.javaforever.clocksimplejee4.service.PrivilegeService;
import com.javaforever.clocksimplejee4.service.UserService;
import com.javaforever.clocksimplejee4.serviceimpl.PrivilegeServiceImpl;
import com.javaforever.clocksimplejee4.serviceimpl.UserServiceImpl;
import com.javaforever.clocksimplejee4.utils.AppTokenManager;

import net.sf.json.JSONObject;

public class LoginFacade extends HttpServlet {
	private static final long serialVersionUID = -2572261386886011897L;

	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        UserService userService = new UserServiceImpl();
        PrivilegeService privService = new PrivilegeServiceImpl();
        Map<String, Object> result = new TreeMap<String,Object>();
        try {
	    	User user2 = new User();
	    	User user3 = new User();
	        user2.setEmpid(Long.parseLong(request.getParameter("empid")==null?"0":request.getParameter("empid")));
	        user2.setPassword(request.getParameter("password"));
	        user2.setUsername(request.getParameter("username"));
	        boolean islogin = false;
	        
	        if (user2.getEmpid() > 0L){
	        	islogin = userService.login(user2);
	        	user3 = userService.getUserByEmpid(user2);
	        	user3.setPassword("");
	        	user3.setConfirmpassword("");
	        	user3.setPin("");
	        	request.getSession(true).setAttribute("userData", user3);
	        	request.getSession(true).setAttribute("islogin", "Y");
	        	request.getSession(true).setAttribute("empid", user3.getEmpid());
	        } else if (user2.getUsername()!= null && !"".equalsIgnoreCase(user2.getUsername())){
	        	islogin = userService.loginViaUserNamePassword(user2);
	        	user3 = userService.getUserByUsername(user2);
	        	user3.setPassword("");
	        	user3.setConfirmpassword("");
	        	user3.setPin("");
	        	request.getSession(true).setAttribute("userData", user3);
	        	request.getSession(true).setAttribute("islogin", "Y");
	        	request.getSession(true).setAttribute("empid", user3.getEmpid());
	    	} else {
	        	request.getSession(true).setAttribute("userData","");
	        	request.getSession(true).setAttribute("islogin", "");
	        	request.getSession(true).setAttribute("empid", "");
	        	result.put("success", false);
	        	out.println(JSONObject.fromObject(result));
	        	return;
	    	}
	        boolean isadmin = "Y".equalsIgnoreCase(user3.getIsadmin()!=null?user3.getIsadmin():"")?true:false;
	        request.getSession(true).setAttribute("isadmin", user3.getIsadmin());
	        
	        System.out.println("Jerry Debug:"+user3.getEmpid()+":"+user3.getUsername()+":"+user3.getPassword());
	        String forwardUrl = request.getRequestURI();
	        System.out.println(forwardUrl);
	        String[] forwards = forwardUrl.split("/");
	        String forwardUrl0 = "";
	        if (forwards.length >= 2){
	        	forwardUrl0 = "../"+forwards[forwards.length-2]+"/"+forwards[forwards.length-1];
	        	System.out.println("Jerry Debug::"+forwardUrl0);
	        } else {
	        	result.put("success", false);
	        	out.println(JSONObject.fromObject(result));
	        	return;
	        }	     
	        boolean canAccess = privService.canAccess(user3, forwardUrl0);
	        Set<String> canAccessUrls = privService.listMyPrivilegeUrls(isadmin);
	        
	    	request.getSession().setAttribute("canAccess", canAccess==true?"Y":"N");
	    	if (islogin && isadmin &&canAccess){
	    		result.put("forwardUrl","../jsp/adminhomepage.jsp");
	    		String token = AppTokenManager.addUserId(user3.getId(),canAccessUrls);
	    		result.put("success", true);
	    		result.put("token", token);
	    		result.put("user", user3);
	        	out.println(JSONObject.fromObject(result));
	        	return;
	    	} else if (islogin){
	    		result.put("forwardUrl","../jsp/userhomepage.jsp");
	    		String token = AppTokenManager.addUserId(user3.getId(),canAccessUrls);
	    		result.put("success", true);
	    		result.put("token", token);
	    		result.put("user", user3);
	        	out.println(JSONObject.fromObject(result));
	        	return;
	    	} else {
	        	request.getSession(true).setAttribute("userData","");
	        	request.getSession(true).setAttribute("islogin", "");
	        	request.getSession(true).setAttribute("empid", "");
	    		result.put("forwardUrl","../login/index.html");
	    		result.put("success", false);
	        	out.println(JSONObject.fromObject(result));
	        	return;
	    	}
        } catch (Exception e){
        	e.printStackTrace();
        	result.put("success", false);
        	out.println(JSONObject.fromObject(result));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
        
    }


    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }


    @Override
    public String getServletInfo() {
        return "Short description";
    }

}


